package com.yuanfeng.userms.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.base.MemberMessageListIntegralDTO;
import com.yuanfeng.commoms.dto.userms.UserInfoDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.vo.activity.RedTemplateEntityVO;
import com.yuanfeng.commoms.vo.activity.YfRedpacketTemplateVO;
import com.yuanfeng.commoms.vo.base.PlusEquityEntityVO;
import com.yuanfeng.commoms.vo.base.PlusThaliEntityVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.userms.entity.UserPlusInfoEntity;
import com.yuanfeng.userms.feign.ActivityServiceClient;
import com.yuanfeng.userms.feign.BaseServiceClient;
import com.yuanfeng.userms.feign.ThirdPartyServiceClient;
import com.yuanfeng.userms.mapper.*;
import com.yuanfeng.userms.service.UserInfoService;
import com.yuanfeng.userms.service.UserPlusInfoService;
import com.yuanfeng.userms.service.UserPointsLogService;
import com.yuanfeng.userms.vo.PlusMemberInfoVO;
import com.yuanfeng.userms.vo.PlusRenewEntityVO;
import com.yuanfeng.userms.vo.PlusRuleEntityVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 */
@Service
public class UserPlusInfoServiceImpl extends ServiceImpl<UserPlusInfoMapper, UserPlusInfoEntity>
    implements UserPlusInfoService {

    @Value("${system.pcIndexConfig}")
    private String pcIndexConfig;

    private static String pcIndexConfig2;


    @PostConstruct
    public String getPcIndexConfig2() {
        return pcIndexConfig2 = this.pcIndexConfig;
    }

    @Autowired
    private UserPlusEquityMapper userPlusEquityMapper;
    @Autowired
    private UserPlusEquityTempMapper userPlusEquityTempMapper;
    @Autowired
    private UserPlusRenewMapper userPlusRenewMapper;
    @Autowired
    private UserPlusOrderMapper userPlusOrderMapper;
    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;
    @Autowired
    private BaseServiceClient baseServiceClientl;
    @Autowired
    private ObjectMapper mapper;
    @Autowired
    private ActivityServiceClient activityServiceClient;
    @Autowired
    private UserPlatformMessageMapper userPlatformMessageMapper;
    @Autowired
    private UserInfoServiceImpl userInfoServiceImpl;
    @Autowired
    private UserPointsLogServiceImpl userPointsLogServiceImpl;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserPointsLogService userPointsLogService;
    @Autowired
    private BaseServiceClient baseServiceClient;



    @Override
    public ResponseResult selectByUserId(Map<String, String> map) {
        UserPlusInfoEntity entity = this.baseMapper.selectOne(new LambdaUpdateWrapper<UserPlusInfoEntity>()
                .eq(map.containsKey("userId"), UserPlusInfoEntity::getUserId, map.containsKey("userId") ? map.get("userId").toString() : null));
        return ResponseResult.success(entity);
    }

    @Override
    public ResponseResult queryUserPlusInfo(String userId) {
        ResponseResult ResponseResult = new ResponseResult();
        BigDecimal bigDecimal1 = new BigDecimal(0);
        UserPlusInfoEntity map1 = this.baseMapper.selectplusmember(userId);
        if (map1 != null) {
            Integer integer = map1.getThaliType();
            String used_amount = String.valueOf(map1.getUsedAmount());
            //用户已用额度
            BigDecimal bigDecimal = new BigDecimal(used_amount);
            BigDecimal subtract = new BigDecimal(0);

            String selectplusthali = map1.getPlusEquity();
            if (selectplusthali == null || selectplusthali == "") {
                return ResponseResult.fail(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
            }
            String[] split = selectplusthali.split(",");
            List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());

            List<PlusEquityEntityVO> entities = userPlusEquityMapper.selectplusequitys(appIdList);
            List<PlusEquityEntityVO> entities1 = userPlusEquityTempMapper.selectplusequitys(appIdList);
            entities.addAll(entities1);
            entities = entities.stream().distinct().collect(Collectors.toList());

            if (entities == null || !(entities.size() > 0)) {
                return ResponseResult.fail(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
            }
            for (PlusEquityEntityVO selectplusequity : entities) {
                if (selectplusequity.getEquityType() == 1) {
                    String equityValue = selectplusequity.getEquityValue();
                    bigDecimal1 = new BigDecimal(equityValue);
                    if (selectplusequity.getDiscountLimit().compareTo(new BigDecimal(0)) == 0) {
                        subtract = new BigDecimal(-1);
                    } else {
                        subtract = selectplusequity.getDiscountLimit().subtract(bigDecimal);
                    }
                }
            }
            Map<String, BigDecimal> result = new HashMap<>();
            result.put("discount", bigDecimal1);
            result.put("residualLimit", subtract.setScale(2, BigDecimal.ROUND_DOWN));
            return ResponseResult.success(result);
        }
        ResponseResult.setCode(5);
        return ResponseResult;
    }

    @Override
    public ResponseResult updateUserPluslimit(HashMap<Object, Object> map) {
        this.baseMapper.updateUserPluslimit(map);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult plusMemberOpen(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());

        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        String userId = userInfo.getUserId();
        //判断用户是续费还是开通
        Date startTime = null;
        PlusMemberInfoVO plusMemberInfo = this.baseMapper.selectByUserId(userId);
        if (plusMemberInfo == null){
            //用户第一次开通
            startTime = new Date();
        }else if (plusMemberInfo != null && plusMemberInfo.getThaliStatus() == 0){
            //会员过期
            startTime = new Date();
        }else if (plusMemberInfo != null && plusMemberInfo.getThaliStatus() == 1){
            //会员未过期续费
            //查询最新续费记录
            PlusRenewEntityVO plusRenewEntity = userPlusRenewMapper.selectRenewNew(userId);
            if (plusRenewEntity == null){
                startTime = plusMemberInfo.getThaliEndtime();
            }else{
                startTime = plusRenewEntity.getRenewEndtime();
            }

        }
        //获取时间
        Calendar instance = Calendar.getInstance();
        int month = instance.get(Calendar.MONTH) + 1;//当前月份

        Date endTime = null;
        String result1 = null;
        instance.setTime(startTime);
        if (map.get("thaliType").equals(CommonType.plusThaliType.PLUS_THALI_MOON.getCode())){
            //月卡
            instance.add(Calendar.MONTH,1);
            endTime = instance.getTime();
            result1 =CommonType.plusThaliType.PLUS_THALI_MOON.getDesc();
        }else if(map.get("thaliType").equals(CommonType.plusThaliType.PLUS_THALI_SEASON.getCode())){
            //季卡
            instance.add(Calendar.MONTH,3);
            endTime = instance.getTime();
            result1 =CommonType.plusThaliType.PLUS_THALI_SEASON.getDesc();
        }else if (map.get("thaliType").equals(CommonType.plusThaliType.PLUS_THALI_YEAR.getCode())){
            //年卡
            instance.add(Calendar.YEAR,1);
            endTime = instance.getTime();
            result1 =CommonType.plusThaliType.PLUS_THALI_YEAR.getDesc();
        }

        try {

            //向订单表加入数据
            Integer integer1 = 0;
            HashMap<String, Object> payMap = new HashMap<>();
            payMap.put("plusOrderid", map.get("plusOrder"));
            payMap.put("userId", userId);
            payMap.put("payPrice", map.get("payPrice"));
            payMap.put("payType", map.get("type"));
            payMap.put("thaliType", map.get("thaliType"));
            payMap.put("startTime", startTime);
            payMap.put("endTime", endTime);
            payMap.put("plusEquity", map.get("thaliEquity"));
            integer1 = userPlusOrderMapper.insertplusorder(payMap);

            Integer integer2 = 0;
            Integer integer3 = 0;

            HashMap<String, Object> renew = new HashMap<>();
            renew.put("userId", userId);
            renew.put("thaliType", map.get("thaliType"));
            renew.put("renewStarttime", startTime);
            renew.put("renewEndtime", endTime);
            renew.put("plusEquity", map.get("thaliEquity"));
            renew.put("plusOrderid", map.get("plusOrder"));

            //向plusinfo插入信息
            if (plusMemberInfo == null){
                //用户第一次开通
                HashMap<String, Object> info = new HashMap<>();
                info.put("userId", userId);
                info.put("thaliType", map.get("thaliType"));
                info.put("thaliStarttime", startTime);
                info.put("thaliEndtime", endTime);
                info.put("redGrantnum", Integer.valueOf(String.valueOf(map.get("thaliType"))) - 1);
                info.put("plusEquity", map.get("thaliEquity"));
                integer2 = this.baseMapper.insertplusinfo(info);

                renew.put("renewStatus", 1);
                integer3 = userPlusRenewMapper.insertplusrenew(renew);

                //刷新token
                userInfo.setThaliType((Integer) map.get("thaliType"));
                userInfo.setPlusMember(1);
                updatetoken(userInfo, String.valueOf(map.get("thaliEquity")),map.get("token").toString());
            }else if (plusMemberInfo != null && plusMemberInfo.getThaliStatus() == 0){
                //会员过期
                HashMap<String, Object> info = new HashMap<>();
                info.put("userId", userId);
                info.put("thaliType", map.get("thaliType"));
                info.put("thaliStarttime", startTime);
                info.put("thaliEndtime", endTime);
                info.put("thaliStatus", 1);
                info.put("redGrantnum", Integer.valueOf(String.valueOf(map.get("thaliType"))) - 1);
                info.put("plusEquity", map.get("thaliEquity"));
                info.put("usedAmount", 0);
                integer2 = this.baseMapper.updateplusinfo(info);

                renew.put("renewStatus", 1);
                integer3 = userPlusRenewMapper.insertplusrenew(renew);
                //刷新token
                userInfo.setThaliType((Integer) map.get("thaliType"));
                userInfo.setPlusMember(1);
                updatetoken(userInfo, String.valueOf(map.get("thaliEquity")),map.get("token").toString());
            }else if (plusMemberInfo != null && plusMemberInfo.getThaliStatus() == 1){
                //会员未过期续费 向续费表插入数据
                renew.put("renewStatus", 0);
                integer3 = userPlusRenewMapper.insertplusrenew(renew);
            }

            //更新短信通知状态
            this.baseMapper.updateplusinfo1(userId);


            //短信通知
            String userMobile = userInfo.getUserMobile();
            Map<String,String> sendMap = new HashMap<>();
            sendMap.put("userMobile",userMobile);
            sendMap.put("content",result1);
            thirdPartyServiceClient.plusmemberopenSend(sendMap);

            //删除首页缓存
            RedisUtil.remove(RedisPrefixUtils.pcIndexConfig + "_" + userId);

            //开通成功发放红包和积分
            if (integer1 > 0 && integer2 > 0){
                //查询套餐
                if (map.get("thaliEquity") != null && map.get("thaliEquity") != ""){
                    String thaliEquity = String.valueOf(map.get("thaliEquity"));
                    String[] split = thaliEquity.split(",");
                    List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());

                    //查询套餐权益
                    List<PlusEquityEntityVO> entities = userPlusEquityMapper.selectplusequity(appIdList);
                    if (entities != null && entities.size() > 0){
                        for (PlusEquityEntityVO entity : entities) {
                            //发放红包
                            if (entity.getEquityType().equals(CommonType.plusEquityType.PLUS_NO_THRESHOLD_REDPAPER.getCode())
                                    || entity.getEquityType().equals(CommonType.plusEquityType.PLUS_RED_PAPER.getCode())){
                                String equityValue = entity.getEquityValue();
                                String[] red = equityValue.split(",");
                                //红包模板id
                                List<Integer> redList = Stream.of(red).map(Integer::parseInt).collect(Collectors.toList());
                                Integer integer = redGrant(userInfo, redList);

                                HashMap<String, Object> map1 = new HashMap<>();
                                map1.put("userId", userId);
                                map1.put("redGrantmonth", month);
                                this.baseMapper.updateplusinfo(map1);

                                //发送站内信通知
                                StringBuffer Content = new StringBuffer(CommonType.plusThaliType.PLUS_CONTENT1.getDesc());
                                StringBuffer Content1 = new StringBuffer(CommonType.plusThaliType.PLUS_CONTENT2.getDesc());

                                Map send = new HashMap<>();
                                if (map.get("thaliType").equals(CommonType.plusThaliType.PLUS_THALI_MOON.getCode())){
                                    Content.append(CommonType.plusThaliType.PLUS_THALI_MOON.getDesc());
                                }else if (map.get("thaliType").equals(CommonType.plusThaliType.PLUS_THALI_SEASON.getCode())){
                                    Content.append(CommonType.plusThaliType.PLUS_THALI_SEASON.getDesc());
                                }else if (map.get("thaliType").equals(CommonType.plusThaliType.PLUS_THALI_YEAR.getCode())){
                                    Content.append(CommonType.plusThaliType.PLUS_THALI_YEAR.getDesc());
                                }
                                Content.append(Content1);
                                send.put("userId",userId);
                                send.put("messageTitle",CommonType.plusThaliType.PLUS_CONTENT3.getDesc());
                                send.put("messageContent",Content.toString());
                                sendmessage(send);

                                if (integer == 2){
                                    return ResponseResult.fail(0, "红包发放失败");
                                }
                            }else if (entity.getEquityType().equals(CommonType.plusEquityType.PLUS_INTEGRAL.getCode())){
                                //发放积分
                                String equityValue = entity.getEquityValue();
                                Integer integer = updateIntegral(userInfo, Integer.parseInt(equityValue), String.valueOf(map.get("plusOrder")));
                                if (integer == 2){
                                    return ResponseResult.fail(0, "积分发放失败");
                                }

                                //修改获取积分
                                Map<String,Object> map1 = new HashMap<>();
                                map1.put("userId",userId);
                                map1.put("earnPoints",equityValue);
                                Integer integer4 = this.baseMapper.updateplusinfo(map1);
                                if (!(integer4 > 0)){
                                    return ResponseResult.fail(0, "积分发放失败");
                                }
                            }
                        }
                    }
                }
            }
            if (integer3 > 0){
                return ResponseResult.success("续费成功");
            }
            if (integer1 > 0 && integer2 > 0){
                return ResponseResult.success("开通成功");
            }
        }catch (Exception e) {
            throw e;
        }
        return ResponseResult.fail(0, "开通失败");
    }

    //开通会员成功更新token信息
    public void updatetoken(UserInfoVO userInfo,String plusEquity,String token){
        Map<String,Object> pmap= (Map<String, Object>) baseServiceClientl.getMemberClassIdByUserId(userInfo.getUserId()).getData();
        int i =Integer.valueOf(pmap.get("memberClassId").toString());
        Map<String, Object> memberClassIdByUserId = (Map<String, Object>) baseServiceClientl.getMemberNameByClassId(String.valueOf(i)).getData();

        //会员折扣
        BigDecimal discount = new BigDecimal(String.valueOf(memberClassIdByUserId.get("gradeDiscount")));
        String[] split = plusEquity.split(",");
        List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());

        //查询权益详情
        List<PlusEquityEntityVO> selectplusequitys = userPlusEquityMapper.selectplusequitys(appIdList);
        if (selectplusequitys != null && selectplusequitys.size() > 0) {
            for (PlusEquityEntityVO plusequity : selectplusequitys) {
                if (plusequity.getEquityType() == 1) {
                    String equityValue = plusequity.getEquityValue();
                    BigDecimal bigDecimal1 = new BigDecimal(equityValue);
                    userInfo.setPlusDiscount(bigDecimal1);//折扣
                }
            }
        }
        // 把用户信息根据根据token存在redis中
        // 用户信息和卖家信息都保存在userinfo中
        try {
            UserInfoDTO userInfoDTO = new UserInfoDTO();
            userInfoDTO.setUser(userInfo);
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + token, mapper.writeValueAsString(userInfoDTO),
                    YFConfig.TOKEN_OUTTIME);
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USERID + token, userInfo.getUserId().toString(),
                    YFConfig.TOKEN_OUTTIME);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
    //发放红包
    @Transactional
    public Integer redGrant(UserInfoVO userInfo,List<Integer> id){
        List<YfRedpacketTemplateVO> newRedpacketTems = activityServiceClient.selectNewRedpacketTem(id);
        if (newRedpacketTems.size() > 0 && newRedpacketTems != null) {
            try {
                for (YfRedpacketTemplateVO newRedpacketTem : newRedpacketTems) {
                    if (newRedpacketTem.getRedTermofvalidity() != null){
                        Calendar instance = Calendar.getInstance();
                        Date redpacketStartDate = new Date();//开始时间
                        instance.setTime(redpacketStartDate);
                        instance.add(Calendar.DATE,newRedpacketTem.getRedTermofvalidity());
                        Date redpacketEndDate = instance.getTime();//结束时间

                        Map<String, Object> insertMap = new HashMap<String, Object>();
                        insertMap.put("redpacketOwnerId", userInfo.getUserId());
                        insertMap.put("redpacketOwnerName", userInfo.getUserName());
                        insertMap.put("redpacketTId", newRedpacketTem.getRedpacketTId());
                        insertMap.put("redpacketTitle", newRedpacketTem.getRedpacketTTitle());
                        insertMap.put("redpacketDesc", newRedpacketTem.getRedpacketTDesc());
                        insertMap.put("redpacketStartDate", redpacketStartDate);
                        insertMap.put("redpacketEndDate", redpacketEndDate);
                        insertMap.put("redpacketPrice", newRedpacketTem.getRedpacketTPrice());
                        insertMap.put("shopLimit", newRedpacketTem.getShopLimit());
                        insertMap.put("goodsCatLimit", newRedpacketTem.getGoodsCatLimit());
                        insertMap.put("redpacketTOrderlimit", newRedpacketTem.getRedpacketTOrderlimit());
                        insertMap.put("macAddress", "");
                        insertMap.put("redpacketType", 7);//plus红包
                        activityServiceClient.insertXinRenYfRedpacketBase(insertMap);

                        // 增加红包已领取数量
                        Map<String, String> updateMap = new HashMap<String, String>();
                        updateMap.put("redpacketTId", newRedpacketTem.getRedpacketTId().toString());

                        activityServiceClient.updateRedpGiveout(updateMap);
                    }
                }
            }catch(Exception e){
                throw e;
            }
        }
        return 1;
    }
    //站内信通知
    public void sendmessage(Map map){
        userPlatformMessageMapper.insertmessage(map);
    }
    public Integer updateIntegral(UserInfoVO userInfo,Integer integral,String orderId){
        //修改会员积分和会员等级
        try {
            MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
            ArrayList<String> list = new ArrayList<>();
            String userId = userInfo.getUserId();
            list.add(userId);
            updateMemberMessageListIntegral.setUserIdList(list);
            updateMemberMessageListIntegral.setIntegral(integral);
            updateMemberMessageListIntegral.setType(CommonType.commonStatus.YES.getCode());//1是增加积分 0 是扣除积分
            userInfoServiceImpl.updateMemberIntegral(updateMemberMessageListIntegral);

            //添加积分修改记录
            Map<String, Object> pointParam = new HashMap<>();
            pointParam.put("PointsLogType", CommonType.pointsLogType.GAIN.getCode().toString());
            pointParam.put("ClassId", CommonType.pointType.PlUS_REMOVE_OBSTACLES.getCode().toString());
            pointParam.put("PointsLogTime", DateUtils.getTime());
            pointParam.put("PointsLogDesc", CommonType.pointType.PlUS_REMOVE_OBSTACLES.getDesc());
            pointParam.put("PointsLogFlag", "reg");
            pointParam.put("UserId", userId);
            pointParam.put("orderId", orderId);
            pointParam.put("PointsLogPoints", integral.toString());
            pointParam.put("PointsLogOperate", CommonType.pointType.PlUS_REMOVE_OBSTACLES.getDesc());
            userPointsLogServiceImpl.insertByMap(pointParam);
        }catch(Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 回滚
            return 2;
        }
        return 1;
    }

    @Override
    public ResponseResult selectPlusMember(Map<String, Object> map) {
        List<PlusThaliEntityVO> plusThaliEntities = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //查询规则
        PlusRuleEntityVO plusRuleEntity = this.baseMapper.selectplusrule();
        if (map.get("token") == null || map.get("token") == ""){
            //用户未登录
            //查询套餐表
            plusThaliEntities = this.baseMapper.selectthaliList();
            if (plusThaliEntities != null && plusThaliEntities.size() > 0){
                for (PlusThaliEntityVO plusThaliEntity : plusThaliEntities) {
                    if (plusRuleEntity != null) {
                        if (plusThaliEntity.getThaliType() == 1) {
                            plusThaliEntity.setLogoImg(plusRuleEntity.getPlusMonthcardlogo());
                        } else if (plusThaliEntity.getThaliType() == 2) {
                            plusThaliEntity.setLogoImg(plusRuleEntity.getPlusSeasoncardlogo());
                        }
                        if (plusThaliEntity.getThaliType() == 3) {
                            plusThaliEntity.setLogoImg(plusRuleEntity.getPlusYearcardlogo());
                        }

                        plusThaliEntity.setRecommend(plusRuleEntity.getPlusSigns());
                        plusThaliEntity.setPropaganda(plusRuleEntity.getPlusPropaganda());
                    }

                    String thaliEquity = plusThaliEntity.getThaliEquity();
                    String[] split = thaliEquity.split(",");
                    List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());
                    plusThaliEntity.setThaliEquityList(appIdList);
                    //查询权益
                    List<PlusEquityEntityVO> selectplusequitys = userPlusEquityMapper.selectplusequitys(appIdList);
                    plusThaliEntity.setEquityTotal(selectplusequitys.size());
                    plusThaliEntity.setPlusEquitys(selectplusequitys);
                    if (selectplusequitys.size() > 0 && selectplusequitys != null){
                        for (PlusEquityEntityVO plusEquityEntity : selectplusequitys) {
                            //获取红包模板
                            if (plusEquityEntity.getEquityType() == 2 || plusEquityEntity.getEquityType() == 3){
                                String equityValue = plusEquityEntity.getEquityValue();
                                String[] split1 = equityValue.split(",");
                                List<Integer> redIdList = Stream.of(split1).map(Integer::parseInt).collect(Collectors.toList());
                                //查询红包模板
                                List<RedTemplateEntityVO> redTemplateEntities = activityServiceClient.selectredtemplateId(redIdList);
                                plusEquityEntity.setRedList(redTemplateEntities);
                            }
                            if (plusEquityEntity.getEquityType() == 1){

                                BigDecimal multiply = new BigDecimal(plusEquityEntity.getEquityValue()).multiply(new BigDecimal(10));
                                plusEquityEntity.setEquityValue(multiply.toString());
                            }
                        }
                    }
                }
            }
        }else{
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
            if (null == userInfo) {
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
            }
            String userId = userInfo.getUserId();

            PlusThaliEntityVO plusThaliEntity = this.baseMapper.selectthaliId(userId);
            if (plusThaliEntity == null){
                return ResponseResult.fail(BizCodeEnume.PLUS_MEMBER_NO_EXIST.getCode(),BizCodeEnume.PLUS_MEMBER_NO_EXIST.getMsg());
            }
            plusThaliEntity.setRedAvailable(0);
            //查询是否有续费权益
            Integer integer = userPlusRenewMapper.selectthaliIdnext(userId);
            plusThaliEntity.setNextThaliType(integer);
            //查询权益最后到期时间
            Map map1 = userPlusRenewMapper.selectthaliIdnexttime(userId);
            if (integer == null){
                //判断是否快到期
                if (plusThaliEntity.getThaliType() == 1){
                    //套餐结束时间
                    Date thaliEndtime = plusThaliEntity.getThaliEndtime();
                    Calendar instance = Calendar.getInstance();
                    instance.setTime(thaliEndtime);
                    instance.add(Calendar.DATE,-5);
                    Date time = instance.getTime();
                    if (new Date().compareTo(time) >= 0){
                        plusThaliEntity.setRenewalDisplay(1);
                    }
                }else if (plusThaliEntity.getThaliType() == 2){
                    //套餐结束时间
                    Date thaliEndtime = plusThaliEntity.getThaliEndtime();
                    Calendar instance = Calendar.getInstance();
                    instance.setTime(thaliEndtime);
                    instance.add(Calendar.MONTH,-1);
                    Date time = instance.getTime();
                    if (new Date().compareTo(time) >= 0){
                        plusThaliEntity.setRenewalDisplay(1);
                    }
                }else if (plusThaliEntity.getThaliType() == 3){
                    //套餐结束时间
                    Date thaliEndtime = plusThaliEntity.getThaliEndtime();
                    Calendar instance = Calendar.getInstance();
                    instance.setTime(thaliEndtime);
                    instance.add(Calendar.MONTH,-3);
                    Date time = instance.getTime();
                    if (new Date().compareTo(time) >= 0){
                        plusThaliEntity.setRenewalDisplay(1);
                    }
                }
            }
            if (plusThaliEntity != null){
                String thaliEquity = plusThaliEntity.getThaliEquity();
                String[] split = thaliEquity.split(",");
                List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());
                plusThaliEntity.setThaliEquityList(appIdList);

                List<PlusEquityEntityVO> selectplusequitys = userPlusEquityMapper.selectplusequitys(appIdList);
                List<PlusEquityEntityVO> selectplusequitys1 = userPlusEquityMapper.selectplusequitysTmp(appIdList);
                selectplusequitys.addAll(selectplusequitys1);
                selectplusequitys =  selectplusequitys.stream().distinct().collect(Collectors.toList());

                plusThaliEntity.setEquityTotal(selectplusequitys.size());
                plusThaliEntity.setPlusEquitys(selectplusequitys);
                if (selectplusequitys.size() > 0 && selectplusequitys != null){
                    for (PlusEquityEntityVO plusEquityEntity : selectplusequitys) {
                        //获取红包模板
                        if (plusEquityEntity.getEquityType() == 2 || plusEquityEntity.getEquityType() == 3){
                            String equityValue = plusEquityEntity.getEquityValue();
                            String[] split1 = equityValue.split(",");
                            List<Integer> redIdList = Stream.of(split1).map(Integer::parseInt).collect(Collectors.toList());
                            //查询红包模板
                            List<RedTemplateEntityVO> redTemplateEntities = activityServiceClient.selectredtemplateId(redIdList);
                            plusEquityEntity.setRedList(redTemplateEntities);

                            if (plusEquityEntity.getEquityType() == 3){
                                plusThaliEntity.setRedTotal(redIdList.size());
                                //判断红包可用张数
                                Integer selectuserred = activityServiceClient.selectuserred(redIdList, userId);
                                plusThaliEntity.setRedAvailable(selectuserred);
                            }
                        }
                        if (plusEquityEntity.getEquityType() == 1){
                            BigDecimal multiply = new BigDecimal(plusEquityEntity.getEquityValue()).multiply(new BigDecimal(10));
                            plusEquityEntity.setEquityValue(multiply.toString());
                        }
                    }
                }
            }
            //有续费权益将到期时间替换
            if (map1 != null){
                try {
                    plusThaliEntity.setThaliEndtime(format.parse(String.valueOf(map1.get("renew_endtime"))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            plusThaliEntities.add(plusThaliEntity);
        }
        return ResponseResult.success(plusThaliEntities);
    }
    @Override
    public ResponseResult openMember(Map<String, Object> map) throws IllegalAccessException {
        String userInfoStr = RedisUtil.get(YFConfig.YF_PLATFORM_TOKEN_USER + map.get("token"));
        if (null == userInfoStr || userInfoStr.equals("")) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

        //查询套餐权益
        ResponseResult selectthalitype = baseServiceClient.queryMerchantPlusThali(map);
        Map<String, Object> thaliMap = (Map) selectthalitype.getData();

        HashMap<String, Object> returnmap = new HashMap<>();
        List userId = (List) map.get("userId");
        //失败用户id
        ArrayList<Object> list = new ArrayList<>();
        for (Object o : userId) {
            //创建支付单号
            int i = PayToolUtil.buildRandom(6);
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            StringBuffer plusorder = new StringBuffer("PLUS");
            plusorder.append(format.format(new Date()));
            plusorder.append(i);
            //获取用户手机号
            String selectphone = this.baseMapper.selectPhone((String) o);
            returnmap.put("userId", o);
            returnmap.put("type", 5);
            returnmap.put("payPrice", 0);
            returnmap.put("thaliType", map.get("thaliType"));
            returnmap.put("plusOrder", plusorder.toString());
            returnmap.put("thaliEquity", thaliMap.get("thaliEquity"));
            returnmap.put("userMobile", selectphone);
            ResponseResult plusmemberopen = openPlusMember(returnmap);
            if (plusmemberopen.getCode() != 1) {
                list.add(o);
            }
        }
        return ResponseResult.success(list);
    }
    //plus会员开通
    public ResponseResult openPlusMember(Map<String, Object> map) {

        String userId = String.valueOf(map.get("userId")) ;
        UserInfoVO userInfo = new UserInfoVO();
        userInfo.setUserId(userId);
        userInfo.setUserName(this.baseMapper.queryUserName(userId));
        //判断用户是续费还是开通
        Date startTime = null;
        PlusMemberInfoVO plusMemberInfo = this.baseMapper.selectByUserId(userId);
        if (plusMemberInfo == null){
            //用户第一次开通
            startTime = new Date();
        }else if (plusMemberInfo != null && plusMemberInfo.getThaliStatus() == 0){
            //会员过期
            startTime = new Date();
        }else if (plusMemberInfo != null && plusMemberInfo.getThaliStatus() == 1){
            //会员未过期续费
            //查询最新续费记录
            PlusRenewEntityVO plusRenewEntity = userPlusRenewMapper.selectRenewNew(userId);
            if (plusRenewEntity == null){
                startTime = plusMemberInfo.getThaliEndtime();
            }else{
                startTime = plusRenewEntity.getRenewEndtime();
            }

        }
        //获取时间
        Calendar instance = Calendar.getInstance();
        int month = instance.get(Calendar.MONTH) + 1;//当前月份

        Date endTime = null;
        instance.setTime(startTime);
        String result1 = null;
        if (map.get("thaliType").equals(1)){
            //月卡
            instance.add(Calendar.DAY_OF_MONTH,30);
            endTime = instance.getTime();
            result1 = "月卡";
        }else if(map.get("thaliType").equals(2)){
            //季卡
            instance.add(Calendar.DAY_OF_MONTH,30 * 3);
            endTime = instance.getTime();
            result1 = "季卡";
        }else if (map.get("thaliType").equals(3)){
            //年卡
            instance.add(Calendar.DAY_OF_MONTH,30 * 12);
            endTime = instance.getTime();
            result1 = "年卡";
        }

        try {

            //向订单表加入数据
            Integer integer1 = 0;
            HashMap<String, Object> payMap = new HashMap<>();
            payMap.put("plusOrderid", map.get("plusOrder"));
            payMap.put("userId", userId);
            payMap.put("payPrice", map.get("payPrice"));
            payMap.put("payType", map.get("type"));
            payMap.put("thaliType", map.get("thaliType"));
            payMap.put("startTime", startTime);
            payMap.put("endTime", endTime);
            payMap.put("plusEquity", map.get("thaliEquity"));
            integer1 = userPlusOrderMapper.insertplusorder(payMap);

            Integer integer2 = 0;
            Integer integer3 = 0;
            //向plusinfo插入信息
            if (plusMemberInfo == null){
                //用户第一次开通
                HashMap<String, Object> info = new HashMap<>();
                info.put("userId", userId);
                info.put("thaliType", map.get("thaliType"));
                info.put("thaliStarttime", startTime);
                info.put("thaliEndtime", endTime);
                info.put("redGrantnum", Integer.valueOf(String.valueOf(map.get("thaliType"))) - 1);
                info.put("plusEquity", map.get("thaliEquity"));
                integer2 = this.baseMapper.insertplusinfo(info);
            }else if (plusMemberInfo != null && plusMemberInfo.getThaliStatus() == 0){
                //会员过期
                HashMap<String, Object> info = new HashMap<>();
                info.put("userId", userId);
                info.put("thaliType", map.get("thaliType"));
                info.put("thaliStarttime", startTime);
                info.put("thaliEndtime", endTime);
                info.put("thaliStatus", 1);
                info.put("redGrantnum", Integer.valueOf(String.valueOf(map.get("thaliType"))) - 1);
                info.put("plusEquity", map.get("thaliEquity"));
                info.put("usedAmount", 0);
                integer2 = this.baseMapper.updateplusinfo(info);
            }else if (plusMemberInfo != null && plusMemberInfo.getThaliStatus() == 1){
                //会员未过期续费 向续费表插入数据
                HashMap<String, Object> renew = new HashMap<>();
                renew.put("userId", userId);
                renew.put("thaliType", map.get("thaliType"));
                renew.put("renewStarttime", startTime);
                renew.put("renewEndtime", endTime);
                renew.put("plusEquity", map.get("thaliEquity"));
                renew.put("plusOrderid", map.get("plusOrder"));
                integer3 = userPlusRenewMapper.insertplusrenew(renew);
            }

            if (plusMemberInfo != null) {
                //更新短信通知状态
                this.baseMapper.updateplusinfo1(userId);
            }

            //发送短信通知
            String userMobile = String.valueOf(map.get("userMobile"));
            Map<String,String> sendMap = new HashMap<>();
            sendMap.put("userMobile",userMobile);
            sendMap.put("content",result1);
            thirdPartyServiceClient.plusmemberopenSend(sendMap);

            //删除首页缓存
            RedisUtil.remove(this.pcIndexConfig2 + "_" + userId);

            //开通成功发放红包和积分
            if (integer1 > 0 && integer2 > 0){
                //查询套餐
                //PlusThaliEntity thali = plusMemberMapper.selectthalitype((Integer) map.get("thaliType"));
                if (map.get("thaliEquity") != null && map.get("thaliEquity") != ""){
                    String thaliEquity = String.valueOf(map.get("thaliEquity"));
                    String[] split = thaliEquity.split(",");
                    List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());
                    //thali.setThaliEquityList(appIdList);

                    //查询套餐权益
                    List<PlusEquityEntityVO> entities = userPlusEquityMapper.selectplusequity(appIdList);
                    if (entities != null && entities.size() > 0){
                        for (PlusEquityEntityVO entity : entities) {
                            //发放红包
                            if (entity.getEquityType() == 2 || entity.getEquityType() == 3){
                                String equityValue = entity.getEquityValue();
                                String[] red = equityValue.split(",");
                                //红包模板id
                                List<Integer> redList = Stream.of(red).map(Integer::parseInt).collect(Collectors.toList());
                                Integer integer = redGrant(userInfo, redList);

                                HashMap<String, Object> map1 = new HashMap<>();
                                map1.put("userId", userId);
                                map1.put("redGrantmonth", month);
                                this.baseMapper.updateplusinfo(map1);

                                //发送站内信通知
                                StringBuffer Content = new StringBuffer(CommonType.plusThaliType.PLUS_CONTENT1.getDesc());
                                StringBuffer Content1 = new StringBuffer(CommonType.plusThaliType.PLUS_CONTENT2.getDesc());
                                Map send = new HashMap<>();
                                if (map.get("thaliType").equals(CommonType.plusThaliType.PLUS_THALI_MOON.getCode())){
                                    Content.append(CommonType.plusThaliType.PLUS_THALI_MOON.getDesc());
                                }else if (map.get("thaliType").equals(CommonType.plusThaliType.PLUS_THALI_SEASON.getCode())){
                                    Content.append(CommonType.plusThaliType.PLUS_THALI_SEASON.getDesc());
                                }else if (map.get("thaliType").equals(CommonType.plusThaliType.PLUS_THALI_YEAR.getCode())){
                                    Content.append(CommonType.plusThaliType.PLUS_THALI_YEAR.getDesc());
                                }
                                Content.append(Content1);
                                send.put("userId",userId);
                                send.put("messageTitle",CommonType.plusThaliType.PLUS_CONTENT3.getDesc());
                                send.put("messageContent",Content.toString());
                                sendmessage(send);

                                if (integer == 2){
                                    return ResponseResult.fail(2,"红包发放失败");
                                }
                            }else if (entity.getEquityType() == 4){
                                //发放积分
                                String equityValue = entity.getEquityValue();
                                Integer integer = updateIntegral(userInfo, Integer.parseInt(equityValue), String.valueOf(map.get("plusOrder")));
                                if (integer == 2){
                                    return ResponseResult.fail(2,"积分发放失败");
                                }

                                //修改获取积分
                                Map<String,Object> map1 = new HashMap<>();
                                map1.put("userId",userId);
                                map1.put("earnPoints",equityValue);
                                Integer integer4 = this.baseMapper.updateplusinfo(map1);
                                if (!(integer4 > 0)){
                                    return ResponseResult.fail(2,"积分发放失败");
                                }
                            }
                        }
                    }
                }

            }
            if (integer3 > 0){
                return ResponseResult.success(1,"续费成功",map.get("thaliType"));
            }
            if (integer1 > 0 && integer2 > 0){
                return ResponseResult.success(1,"开通成功",map.get("thaliType"));
            }
        }catch (Exception e) {
            throw e;
        }
        return ResponseResult.fail(2,"开通失败",map.get("thaliType"));
    }

    @Override
    public void plusMemberUpdate() {
        //查询过期会员信息
        Map infomap = new HashMap<>();
        Map renewmap = new HashMap<>();
        UserInfoVO userInfo = new UserInfoVO();
        List<PlusMemberInfoVO> selectplus = this.baseMapper.selectplus();
        for (PlusMemberInfoVO plusMemberInfo : selectplus) {

            userInfo.setUserId(plusMemberInfo.getUserId());
            userInfo.setUserName(plusMemberInfo.getUserName());
            //判断该用户是否有续费信息
            PlusRenewEntityVO plusRenewEntity = this.baseMapper.selectRenewNewUser(plusMemberInfo.getUserId());
            if (plusRenewEntity == null){
                //无续费信息 更新plusinfo会员状态
                infomap.put("thaliStatus",0);
                infomap.put("userId",plusMemberInfo.getUserId());
                this.baseMapper.updateplusinfo(infomap);
            }else{
                //将续费信息更新到info
                String plusEquity = plusRenewEntity.getPlusEquity();
                renewmap.put("thaliType",plusRenewEntity.getThaliType());
                renewmap.put("thaliStarttime",plusRenewEntity.getRenewStarttime());
                renewmap.put("thaliEndtime",plusRenewEntity.getRenewEndtime());
                renewmap.put("plusEquity",plusEquity);
                renewmap.put("usedAmount",0);
                renewmap.put("redGrantnum",plusRenewEntity.getThaliType() - 1);
                renewmap.put("userId",plusMemberInfo.getUserId());
                this.baseMapper.updateplusinfo(renewmap);

                //更新续费状态
                userPlusRenewMapper.updaterenew(plusRenewEntity.getRenewId());

                //开通成功发放红包和积分

                //查询套餐
                //PlusThaliEntity thali = plusMemberMapper.selectthalitype((Integer) map.get("thaliType"));
                if (plusEquity != null && plusEquity != ""){
                    String thaliEquity = String.valueOf(plusEquity);
                    String[] split = thaliEquity.split(",");
                    List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());
                    //thali.setThaliEquityList(appIdList);

                    //查询套餐权益
                    List<PlusEquityEntityVO> entities = this.baseMapper.selectplusequity(appIdList);
                    if (entities != null && entities.size() > 0){
                        for (PlusEquityEntityVO entity : entities) {
                            //发放红包
                            if (entity.getEquityType() == 2 || entity.getEquityType() == 3){
                                String equityValue = entity.getEquityValue();
                                String[] red = equityValue.split(",");
                                //红包模板id
                                List<Integer> redList = Stream.of(red).map(Integer::parseInt).collect(Collectors.toList());
                                redGrant(userInfo, redList);

                                //更新红包发放月份
                                Calendar instance = Calendar.getInstance();
                                instance.setTime(new Date());
                                int month = instance.get(Calendar.MONTH) + 1;//当前月份
                                HashMap<String, Object> map = new HashMap<>();
                                map.put("userId", plusMemberInfo.getUserId());
                                map.put("redGrantmonth", month);
                                this.baseMapper.updateplusinfo(map);

                            }else if (entity.getEquityType() == 4){
                                //发放积分
                                String equityValue = entity.getEquityValue();
                                updateIntegral(userInfo, Integer.parseInt(equityValue), plusRenewEntity.getPlusOrderid());

                                //修改获取积分
                                Map<String,Object> map1 = new HashMap<>();
                                map1.put("userId",plusMemberInfo.getUserId());
                                map1.put("earnPoints",equityValue);
                                this.baseMapper.updateplusinfo(map1);
                            }
                        }
                    }

                }
            }
            //清空首页缓存
            RedisUtil.remove(this.pcIndexConfig2 + "_" + plusMemberInfo.getUserId());
        }
    }

    @Override
    public ResponseResult updateLimit() {
        DateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        Map infomap = new HashMap<>();
        Date star = null;//开始时间
        Date endDay = null;//结束时间
        //查询额度不为零的plus会员
        List<PlusMemberInfoVO> selectplusinfo = this.baseMapper.selectplusinfo();
        if (!CollectionUtils.isEmpty(selectplusinfo)) {
            for (PlusMemberInfoVO plusMemberInfo : selectplusinfo) {
                try {
                    star = dft.parse(dft.format(plusMemberInfo.getThaliStarttime()));
                    endDay = dft.parse(dft.format(new Date()));//任务执行时间
                    //当前时间与其他时间相差的毫秒数
                    Long diff = endDay.getTime() - star.getTime();
                    BigDecimal divide = BigDecimal.valueOf(diff).divide
                            (BigDecimal.valueOf(60 * 60 * 1000 * 24), 2, BigDecimal.ROUND_HALF_UP);

                    if (new BigDecimal(divide.intValue()).compareTo(divide) == 0) {
                        //清空每月消费额度
                        BigDecimal divide1 = divide.divide(BigDecimal.valueOf(30), 2, BigDecimal.ROUND_HALF_UP);
                        if (new BigDecimal(divide1.intValue()).compareTo(divide1) == 0) {
                            //更新基础额度
                            infomap.put("userId", plusMemberInfo.getUserId());
                            infomap.put("usedAmount", 0);
                            this.baseMapper.updateplusinfo(infomap);
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }
        }
        return ResponseResult.success();
    }

    @Override
    public void redgrant() {
        //获取时间
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        System.out.println(instance.getTime());
        int year = instance.get(Calendar.YEAR);//当前年份
        int month = instance.get(Calendar.MONTH) + 1;//当前月份
        System.out.println(month);
        Date date = new Date();//当前时间

        StringBuffer Content = new StringBuffer("尊敬的用户，您的PLUS");
        StringBuffer Content1 = new StringBuffer("权益-红包券已到账，请查收！");

        //查询过期会员信息
        Map infomap = new HashMap<>();
        Map send = new HashMap<>();

        UserInfoVO userInfo = new UserInfoVO();
        List<PlusMemberInfoVO> selectplus = this.baseMapper.selectred(month);
        for (PlusMemberInfoVO plusMemberInfo : selectplus) {
            userInfo.setUserId(plusMemberInfo.getUserId());
            userInfo.setUserName(plusMemberInfo.getUserName());
            //开通成功发放红包和积分
            //查询套餐
            String plusEquity = plusMemberInfo.getPlusEquity();
            //PlusThaliEntity thali = plusMemberMapper.selectthalitype((Integer) map.get("thaliType"));
            if (plusEquity != null && plusEquity != "") {
                String thaliEquity = String.valueOf(plusEquity);
                String[] split = thaliEquity.split(",");
                List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());
                //thali.setThaliEquityList(appIdList);

                //查询套餐权益
                List<PlusEquityEntityVO> entities = userPlusEquityMapper.selectplusequity(appIdList);
                if (entities != null && entities.size() > 0) {

                    for (PlusEquityEntityVO entity : entities) {
                        //红包发放日
                        Integer redProvide = entity.getRedProvide();

                        //发放红包
                        if ( entity.getEquityType() == 3) {
                            Calendar instance1 = Calendar.getInstance();
                            int i = instance1.get(Calendar.MONTH);
                            //红包发放时间
                            instance.set(year,i,redProvide,00,00,00);
                            Date redtime = instance.getTime();

                            //到达红包发放日
                            if (date.compareTo(redtime) >= 0) {
                                //发放红包
                                String equityValue = entity.getEquityValue();
                                String[] red = equityValue.split(",");
                                //红包模板id
                                List<Integer> redList = Stream.of(red).map(Integer::parseInt).collect(Collectors.toList());
                                Integer integer = redGrant(userInfo, redList);
                                if (month >= plusMemberInfo.getRedGrantmonth()) {
                                    if (integer == 1) {
                                        //更新红包发放次数
                                        infomap.put("userId", plusMemberInfo.getUserId());
                                        infomap.put("redGrantnum", plusMemberInfo.getRedGrantnum() - 1);
                                        infomap.put("redGrantmonth", month);
                                        this.baseMapper.updateplusinfo(infomap);

                                        //发送站内信通知
                                        if (plusMemberInfo.getThaliType() == 1){
                                            Content.append("月卡");
                                        }else if (plusMemberInfo.getThaliType() == 2){
                                            Content.append("季卡");
                                        }else if (plusMemberInfo.getThaliType() == 3){
                                            Content.append("年卡");
                                        }
                                        Content.append(Content1);
                                        send.put("userId",plusMemberInfo.getUserId());
                                        send.put("messageTitle","红包到账通知");
                                        send.put("messageContent",Content.toString());
                                        sendmessage(send);
                                    }
                                }
                            }
                        }
                    }
                }

            }

        }
    }
}




